using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.Threading;

namespace InfFront.InfoViews.WinForms.Framework
{
    /// <summary>
    /// Detailed exception presentation form
    /// </summary>
    public partial class ExceptionReportForm : Form
    {
        private ExceptionReportForm()
        {
            InitializeComponent();
            if (!pnlDetails.Visible)
                pnlBottom.Height = pnlControls.Height;
        }

        private ExceptionReportForm(string message, string stackTrace)
            : this()
		{
        }

        /// <summary>
        /// Application.ThreadException handler
        /// Tries to show the ExceptionReportForm.
        /// </summary>
        /// <param name="sender">a sender</param>
        /// <param name="t">event arguments</param>
        protected static void OnThreadException(object sender, ThreadExceptionEventArgs t)
        {
            DialogResult result = DialogResult.Cancel;
            try
            {
                result = HandleException(t.Exception);
            }
            catch
            {
                try
                {
                    MessageBox.Show("Fatal Error", "Fatal Error", MessageBoxButtons.AbortRetryIgnore, MessageBoxIcon.Stop);
                }
                finally
                {
                    Application.Exit();
                }
            }

            // Exits the program when the user clicks Abort.
            if (result == DialogResult.Abort)
                Application.Exit();
        }

        /// <summary>
        /// Shows ErrorReportForm to represent the exception.
        /// </summary>
        /// <param name="e">exception instance</param>
        /// <returns>DialogResult.Abort or DialogResult.Ignore</returns>
        public static DialogResult HandleException(Exception e)
        {
            ExceptionReportForm form = new ExceptionReportForm(e.Message, e.StackTrace);
            return form.ShowDialog();
        }

        /// <summary>
        /// Installs the <see cref="ExceptionReportForm.OnThreadException"/>
        /// </summary>
        public static void Install()
        {
            Application.ThreadException += new ThreadExceptionEventHandler(OnThreadException);
        }

        private void lnkDetails_Click(object sender, EventArgs e)
        {
            bool show = !pnlDetails.Visible;
            if (show)
                lnkDetails.Text = "&Hide &details";
            else
                lnkDetails.Text = "&Show &details";
            pnlDetails.Visible = show;
            if (!show)
                pnlBottom.Height = pnlControls.Height;
        }
    }
}